package com.zp2.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zp2.mappers.UserMapper;
import com.zp2.model.user.User;
import com.zp2.model.user.UserLoginVo;
import com.zp2.model.vo.AdminsLoginVo;
import com.zp2.service.UserService;
import com.zp2.util.code.CodeNumber;
import com.zp2.util.result.Result;
import com.zp2.util.result.ResultCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public Result getUserInfo(UserLoginVo userLoginVo) {
        String phone = userLoginVo.getPhone();
        String code = userLoginVo.getCode();

        //判断手机号和验证码是否为空
        if (StringUtils.isEmpty(phone)||StringUtils.isEmpty(code)) {
            return Result.fail(ResultCodeEnum.DATA_ERROR);
        }

        //判断短信验证码是否正确
        String redisCode = redisTemplate.opsForValue().get("phone");
        if(!code.equals(redisCode)){
            return Result.fail(ResultCodeEnum.CODE_ERROR);
        }

        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("phone", phone);
        User user = baseMapper.selectOne(wrapper);
        if(ObjectUtils.isEmpty(user)){
            return Result.fail();
        }
        return Result.ok(user);
    }

    @Override
    public Result getAdminInfo(AdminsLoginVo adminsLoginVo) {
        String username = adminsLoginVo.getUsername();
        String password = adminsLoginVo.getPassword();
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        User user = baseMapper.selectOne(wrapper);
        if(ObjectUtils.isEmpty(user)){
            return Result.fail(ResultCodeEnum.LOGIN_MOBLE_ERROR);
        }else if(!user.getPassword().equals(password)){
            return Result.fail(ResultCodeEnum.PWD_ERROR);
        }
        return Result.ok(user);
    }

    @Override
    public Result smsLogin(String phone) {
        String code = CodeNumber.randomStringGeneratorNumber(6);
        redisTemplate.opsForValue().set("phone",code);
        return Result.ok(code);
    }
}
